package org.zjt.demo.disruptor;

import com.lmax.disruptor.EventTranslator;
import com.lmax.disruptor.dsl.Disruptor;
import org.zjt.demo.model.Trade;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class TradePublisher implements Runnable {

    Disruptor<Trade> disruptor;
    private CountDownLatch latch;
    private String name;

    private static int LOOP=10;//模拟百万次交易的发生

    public TradePublisher(CountDownLatch latch,Disruptor<Trade> disruptor,String name) {
        this.disruptor=disruptor;
        this.latch=latch;
        this.name=name;
    }

    @Override
    public void run() {
        TradeEventTranslator tradeTransloator = new TradeEventTranslator();
        System.out.println("---------------------------------"+name+"-----------------------------------");
        for(int i=0;i<LOOP;i++){
            disruptor.publishEvent(tradeTransloator);
        }
        latch.countDown();
    }

}


/**
 * 生产者产生的消息
 */
class TradeEventTranslator implements EventTranslator<Trade>{
    private Random random=new Random();
    @Override
    public void translateTo(Trade event, long sequence) {
        this.generateTrade(event);
    }

    private Trade generateTrade(Trade trade){
        trade.setPrice(random.nextDouble()*9999);
        return trade;
    }

}  